import pandas as pd
import numpy as np
import warnings
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import FuncFormatter
# 设置 中 文 显 示 字 体
plt.rcParams['font.sans-serif']=['SimHei'] # 用 来 正 常 显 示 中 文 标 签
plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号
warnings.filterwarnings("ignore") #清除警告日志

# 模拟生成数据
np.random.seed(42)
n = 12  # 模拟 12 个月的数据
report_dates = pd.date_range(start='2025-01-01', periods=n, freq='M')

# 原/分保费收入
base_original_premium = 1000000
original_premium_growth_rate = np.random.uniform(0.01, 0.1, n)
original_premium = base_original_premium * (1 + original_premium_growth_rate).cumprod()

# 基期原/分保费收入
base_original_premium_base = np.roll(original_premium, 1)
base_original_premium_base[0] = base_original_premium

# 分出保费
ceded_premium = np.random.uniform(0.1, 0.3, n) * original_premium

# 自留保费
retained_premium = original_premium - ceded_premium

# 基期自留保费
base_retained_premium = np.roll(retained_premium, 1)
base_retained_premium[0] = retained_premium[0]

# 首年原/分保费收入
first_year_premium = np.random.uniform(0.2, 0.5, n) * original_premium

# 长期人身险有效保单数量
initial_policies = 1000
policy_growth_rate = np.random.uniform(-0.05, 0.1, n)
policy_count = initial_policies * (1 + policy_growth_rate).cumprod()

# 个人营销渠道首年原保费收入
personal_channel_premium = np.random.uniform(0.1, 0.3, n) * original_premium

# 个人营销渠道新单件数
personal_channel_new_policies = np.random.randint(100, 500, n)

# 标准保费
standard_premium_coefficient = np.random.uniform(0.8, 1.2, n)
standard_premium = first_year_premium * standard_premium_coefficient

# 基期标准保费
base_standard_premium = np.roll(standard_premium, 1)
base_standard_premium[0] = standard_premium[0]

# 期初和期末营销员数量
initial_agents = 50
agent_growth_rate = np.random.uniform(-0.05, 0.1, n)
agent_count = initial_agents * (1 + agent_growth_rate).cumprod()
end_agent_count = np.roll(agent_count, -1)
end_agent_count[-1] = agent_count[-1]

# 期初和期末所有者权益
initial_equity = 5000000
equity_growth_rate = np.random.uniform(0.01, 0.05, n)
equity = initial_equity * (1 + equity_growth_rate).cumprod()
end_equity = np.roll(equity, -1)
end_equity[-1] = equity[-1]

# 赔付支出
claim_rate = np.random.uniform(0.3, 0.7, n)
claims_payment = claim_rate * retained_premium

# 费用支出
expense_rate = np.random.uniform(0.1, 0.3, n)
expense_payment = expense_rate * original_premium

# 投资收益
investment_rate = np.random.uniform(0.03, 0.08, n)
investment_income = equity * investment_rate

# 创建 DataFrame
data = {
    '报告日期': report_dates,
    '原/分保费收入': original_premium,
    '基期原/分保费收入': base_original_premium_base,
    '分出保费': ceded_premium,
    '自留保费': retained_premium,
    '基期自留保费': base_retained_premium,
    '首年原/分保费收入': first_year_premium,
    '第1个月末长期人身险有效保单数量': np.roll(policy_count, 12),
    '第13个月末长期人身险有效保单数量': policy_count,
    '个人营销渠道首年原保费收入': personal_channel_premium,
    '个人营销渠道新单件数': personal_channel_new_policies,
    '标准保费': standard_premium,
    '基期标准保费': base_standard_premium,
    '期初营销员数量': agent_count,
    '期末营销员数量': end_agent_count,
    '期初所有者权益': equity,
    '期末所有者权益': end_equity,
    '赔付支出': claims_payment,
    '费用支出': expense_payment,
    '投资收益': investment_income
}

df = pd.DataFrame(data)



# 计算各项指标
# 原/分保费收入增长率
df['原/分保费收入增长率'] = ((df['原/分保费收入'] - df['基期原/分保费收入']) / df['基期原/分保费收入']) * 100

# 自留保费增长率
df['自留保费增长率'] = ((df['自留保费'] - df['基期自留保费']) / df['基期自留保费']) * 100

# 首年保费与保费收入比
df['首年保费与保费收入比'] = (df['首年原/分保费收入'] / df['原/分保费收入']) * 100

# 13 个月续保率
df['13 个月续保率'] = (df['第13个月末长期人身险有效保单数量'] / df['第1个月末长期人身险有效保单数量']) * 100

# 个人营销渠道的件均保费
df['个人营销渠道的件均保费'] = df['个人营销渠道首年原保费收入'] / df['个人营销渠道新单件数']

# 标准保费增长率
df['标准保费增长率'] = ((df['标准保费'] - df['基期标准保费']) / df['基期标准保费']) * 100

# 人均保费
df['人均保费'] = df['标准保费'] / ((df['期初营销员数量'] + df['期末营销员数量']) / 2)

# 自留保费占净资产比
df['自留保费占净资产比'] = (df['自留保费'] / ((df['期初所有者权益'] + df['期末所有者权益']) / 2)) * 100

# 赔付率
df['赔付率'] = (df['赔付支出'] / df['自留保费']) * 100

# 费用率
df['费用率'] = (df['费用支出'] / df['原/分保费收入']) * 100

# 综合成本率
df['综合成本率'] = df['赔付率'] + df['费用率']

# 投资收益率
df['投资收益率'] = (df['投资收益'] / ((df['期初所有者权益'] + df['期末所有者权益']) / 2)) * 100

# 承保利润率
df['承保利润率'] = 100 - df['综合成本率']

# 资产收益率
df['资产收益率'] = ((df['投资收益'] + df['自留保费'] - df['赔付支出'] - df['费用支出']) / ((df['期初所有者权益'] + df['期末所有者权益']) / 2)) * 100

# 格式化函数 - 金额格式化
def currency_formatter(x, pos):
    if x >= 1e6:
        return f'{x/1e6:.1f}M'
    elif x >= 1e3:
        return f'{x/1e3:.1f}K'
    return f'{x:.0f}'

# 格式化函数 - 百分比格式化
def percent_formatter(x, pos):
    return f'{x:.1f}%'

# 创建保险业务看板图表
plt.figure(figsize=(16, 18))
plt.suptitle('保险业务看板 (2025年)', fontsize=16, fontweight='bold')

# 保费收入趋势图
ax1 = plt.subplot2grid((4, 2), (0, 0))
ax1.plot(df['报告日期'], df['原/分保费收入'], 'o-', label='原/分保费收入')
ax1.plot(df['报告日期'], df['自留保费'], 's-', label='自留保费')
ax1.plot(df['报告日期'], df['首年原/分保费收入'], 'd-', label='首年原/分保费收入')
ax1.set_title('保费收入趋势')
ax1.set_xlabel('报告日期')
ax1.set_ylabel('金额')
ax1.yaxis.set_major_formatter(FuncFormatter(currency_formatter))
ax1.grid(True, linestyle='--', alpha=0.7)
ax1.legend()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m-%Y'))
plt.xticks(rotation=45)

# 保费收入增长率对比图
ax2 = plt.subplot2grid((4, 2), (0, 1))
ax2.bar(df['报告日期'], df['原/分保费收入增长率'], width=20, label='原/分保费收入增长率')
ax2.bar(df['报告日期'], df['自留保费增长率'], width=15, label='自留保费增长率', alpha=0.7)
ax2.bar(df['报告日期'], df['标准保费增长率'], width=10, label='标准保费增长率', alpha=0.5)
ax2.set_title('保费收入增长率对比')
ax2.set_xlabel('报告日期')
ax2.set_ylabel('增长率 (%)')
ax2.yaxis.set_major_formatter(FuncFormatter(percent_formatter))
ax2.grid(True, linestyle='--', alpha=0.7)
ax2.legend()
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m-%Y'))
plt.xticks(rotation=45)

# 保单数量和营销员数量趋势
ax3 = plt.subplot2grid((4, 2), (1, 0))
ax3.plot(df['报告日期'], df['第13个月末长期人身险有效保单数量'], 'o-', color='blue', label='有效保单数量')
ax3.set_ylabel('保单数量', color='blue')
ax3.tick_params(axis='y', labelcolor='blue')
ax3.grid(True, linestyle='--', alpha=0.7)

ax3_twin = ax3.twinx()
ax3_twin.plot(df['报告日期'], (df['期初营销员数量'] + df['期末营销员数量']) / 2, 's-', color='red', label='平均营销员数量')
ax3_twin.set_ylabel('营销员数量', color='red')
ax3_twin.tick_params(axis='y', labelcolor='red')

ax3.set_title('保单数量和营销员数量趋势')
ax3.set_xlabel('报告日期')
ax3.xaxis.set_major_formatter(mdates.DateFormatter('%m-%Y'))
plt.xticks(rotation=45)

# 创建图例
lines1, labels1 = ax3.get_legend_handles_labels()
lines2, labels2 = ax3_twin.get_legend_handles_labels()
ax3.legend(lines1 + lines2, labels1 + labels2, loc='upper left')

# 业务结构分析
ax4 = plt.subplot2grid((4, 2), (1, 1))
total_premium = df.iloc[-1]['原/分保费收入']
first_year_premium = df.iloc[-1]['首年原/分保费收入']
renewal_premium = total_premium - first_year_premium
ceded_premium = df.iloc[-1]['分出保费']
retained_premium = df.iloc[-1]['自留保费']

premium_parts = [first_year_premium, renewal_premium]
premium_labels = ['首年保费', '续期保费']
premium_colors = ['#ff9999', '#66b3ff']

business_parts = [retained_premium, ceded_premium]
business_labels = ['自留业务', '分出业务']
business_colors = ['#99ff99', '#ffcc99']

ax4.pie(premium_parts, labels=premium_labels, colors=premium_colors, autopct='%1.1f%%', startangle=90)
ax4.axis('equal')
ax4.set_title('保费收入结构分析')

# 费用分析
ax5 = plt.subplot2grid((4, 2), (2, 0))
ax5.plot(df['报告日期'], df['赔付率'], 'o-', label='赔付率')
ax5.plot(df['报告日期'], df['费用率'], 's-', label='费用率')
ax5.plot(df['报告日期'], df['综合成本率'], 'd-', label='综合成本率')
ax5.axhline(y=100, color='r', linestyle='--', label='盈亏平衡点')
ax5.set_title('费用分析')
ax5.set_xlabel('报告日期')
ax5.set_ylabel('百分比 (%)')
ax5.yaxis.set_major_formatter(FuncFormatter(percent_formatter))
ax5.grid(True, linestyle='--', alpha=0.7)
ax5.legend()
ax5.xaxis.set_major_formatter(mdates.DateFormatter('%m-%Y'))
plt.xticks(rotation=45)

# 收益分析
ax6 = plt.subplot2grid((4, 2), (2, 1))
ax6.plot(df['报告日期'], df['投资收益率'], 'o-', label='投资收益率')
ax6.plot(df['报告日期'], df['承保利润率'], 's-', label='承保利润率')
ax6.plot(df['报告日期'], df['资产收益率'], 'd-', label='资产收益率')
ax6.set_title('收益分析')
ax6.set_xlabel('报告日期')
ax6.set_ylabel('收益率 (%)')
ax6.yaxis.set_major_formatter(FuncFormatter(percent_formatter))
ax6.grid(True, linestyle='--', alpha=0.7)
ax6.legend()
ax6.xaxis.set_major_formatter(mdates.DateFormatter('%m-%Y'))
plt.xticks(rotation=45)

# 关键指标雷达图
ax7 = plt.subplot2grid((4, 2), (3, 0), projection='polar')

# 选择最近一个月的数据
latest_data = df.iloc[-1]
metrics = ['原/分保费收入增长率', '自留保费增长率', '13 个月续保率',
           '标准保费增长率', '投资收益率', '资产收益率']
values = [latest_data[m] for m in metrics]

# 闭合数据
metrics = metrics + [metrics[0]]
values = values + [values[0]]

# 角度计算
angles = np.linspace(0, 2*np.pi, len(metrics)-1, endpoint=False).tolist()
angles = angles + [angles[0]]

# 绘制雷达图
ax7.plot(angles, values, 'o-', linewidth=2)
ax7.fill(angles, values, alpha=0.25)

# 设置标签
# 关键指标雷达图
ax7 = plt.subplot2grid((4, 2), (3, 0), projection='polar')

# 选择最近一个月的数据
latest_data = df.iloc[-1]
metrics = ['原/分保费收入增长率', '自留保费增长率', '13 个月续保率',
           '标准保费增长率', '投资收益率', '资产收益率']
values = [latest_data[m] for m in metrics]

# 闭合数据
metrics_for_plot = metrics + [metrics[0]]  # 创建用于绘图的闭合标签列表
values = values + [values[0]]

# 角度计算
angles = np.linspace(0, 2*np.pi, len(metrics), endpoint=False).tolist()
angles = angles + [angles[0]]

# 绘制雷达图
ax7.plot(angles, values, 'o-', linewidth=2)
ax7.fill(angles, values, alpha=0.25)

# 设置标签（使用原始的metrics列表，不含重复值）
ax7.set_thetagrids(np.degrees(angles[:-1]), metrics)
ax7.set_ylim(0, max(values)*1.2)
ax7.set_title('关键指标雷达图')

# 最近一个月的核心指标卡片
ax8 = plt.subplot2grid((4, 2), (3, 1))
ax8.axis('off')

# 选择最近一个月的数据
latest = df.iloc[-1]

# 格式化数据
formatted_data = {
    '原/分保费收入': f"{latest['原/分保费收入']:,.0f}",
    '自留保费': f"{latest['自留保费']:,.0f}",
    '首年保费与保费收入比': f"{latest['首年保费与保费收入比']:.1f}%",
    '13个月续保率': f"{latest['13 个月续保率']:.1f}%",
    '个人营销渠道件均保费': f"{latest['个人营销渠道的件均保费']:,.0f}",
    '赔付率': f"{latest['赔付率']:.1f}%",
    '费用率': f"{latest['费用率']:.1f}%",
    '综合成本率': f"{latest['综合成本率']:.1f}%",
    '投资收益率': f"{latest['投资收益率']:.1f}%",
    '资产收益率': f"{latest['资产收益率']:.1f}%"
}

# 显示数据
table_data = [[k, v] for k, v in formatted_data.items()]
ax8.table(cellText=table_data, loc='center', colLabels=['指标', '数值'])
ax8.set_title('核心指标概览')

plt.tight_layout()
plt.subplots_adjust(top=0.92)
plt.show()

# 打印详细数据
print("="*50)
print("保险业务详细数据")
print("="*50)
print(df[['报告日期', '原/分保费收入', '自留保费', '首年原/分保费收入',
         '原/分保费收入增长率', '自留保费增长率', '首年保费与保费收入比',
         '13 个月续保率', '个人营销渠道的件均保费', '赔付率', '费用率',
         '综合成本率', '投资收益率', '资产收益率']])